package com.yuda.campsite.controller;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.oss.OSS;
import com.aliyun.teaopenapi.models.Config;
import com.yuda.campsite.domain.WeiTiJiaoStudent;
import com.yuda.campsite.domain.WorkForCampsite;
import com.yuda.campsite.dto.WorkForCampsiteParam;
import com.yuda.campsite.service.IWorkForCampsiteServlce;
import com.yuda.campsite.service.WeiTiJiaoStudentService;
import com.yuda.common.core.utils.file.OssFileUtils;
import com.yuda.common.core.web.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * @Author: xiaohudie
 * @Date: 2021/12/7 17:04
 * @Version: 1.8
 */
@RestController
@RequestMapping("/ld")
@Slf4j
public class WorkForCampsiteController {
   @Resource
    private IWorkForCampsiteServlce workForCampsiteServlce;
   @Resource
   private OSS oss;
   @Resource
   private Client client;
   @Resource
   private WeiTiJiaoStudentService weiTiJiaoStudentService;
    /**
     * 时间戳转化工具类
     */
    public static String timeStamp2Date(String seconds, String format) {
        if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
            return "";
        }
        if (format == null || format.isEmpty()) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds + "000")));
    }
   /**判断文件大小的公共接口*/
    public static boolean checkFileSize(long len,int size,String unit){
        double fileSize =0;
        if ("B".equals(unit.toUpperCase())){
            fileSize=(double) len;
        }else if ("K".equals(unit.toUpperCase())){
            fileSize=(double) len/1024;
        }else if ("M".equals(unit.toUpperCase())){
            fileSize=(double) len/1048576;
        }else if ("G".equals(unit.toUpperCase())){
            fileSize=(double) len/1073741824;
        }if (fileSize>size){
            return false;
        }
        return true;
    }
   /**得到已评阅学生的列表*/
   @GetMapping("/yipingyue")
   public Map<String,Object>  ld1(WorkForCampsiteParam workForCampsiteParam) throws ParseException {
       workForCampsiteParam.setQisi((workForCampsiteParam.getQisi()-1)*workForCampsiteParam.getOffset());
       List<WorkForCampsite> workForCampsites1 = workForCampsiteServlce.YiPingYue(workForCampsiteParam);
       /**然后来计算total*/
       workForCampsiteParam.setQisi(0);
       workForCampsiteParam.setOffset(10000);
       List<WorkForCampsite> workForCampsites = workForCampsiteServlce.YiPingYue(workForCampsiteParam);
       int size = workForCampsites.size();
       Map<String,Object> jsonObject =new HashMap<>(4);
       jsonObject.put("code",200);
       jsonObject.put("msg","查询成功");
       jsonObject.put("total",size);
       jsonObject.put("data",workForCampsites);
       return jsonObject;
   }
   /**得到待评阅学生的列表*/
   @GetMapping("/weipingyue")
    public Map<String,Object> weipingyue(WorkForCampsiteParam workForCampsiteParam) throws ParseException {
       workForCampsiteParam.setQisi((workForCampsiteParam.getQisi()-1)*workForCampsiteParam.getOffset());
       List<WorkForCampsite> workForCampsites = workForCampsiteServlce.WeiPingYue(workForCampsiteParam);
       /**设置题号的头根据前段传过来的题号进行拼接*/
       workForCampsiteParam.setStuWorkNum("0");
       String title ="0" +workForCampsiteParam.getStuWorkNum();
       Integer i =1;
       for (WorkForCampsite workForCampsite : workForCampsites) {
           if (i<10) {
               workForCampsite.setWorkNum(title +"000" +i.toString());
           }if (i>=10 && i<100){
               workForCampsite.setWorkNum(title +"00" +i.toString());
           }if (i>=100 && i<1000){
               workForCampsite.setWorkNum(title+"0"+i.toString());
           }if (i>=1000 ){
               workForCampsite.setWorkNum(title+i.toString());
           }
           i++;
       }
       /**然后计算total*/
       workForCampsiteParam.setQisi(0);
       workForCampsiteParam.setOffset(10000);
       List<WorkForCampsite> workForCampsites1 = workForCampsiteServlce.WeiPingYue(workForCampsiteParam);
       int size = workForCampsites1.size();
       Map<String,Object> jsonObject =new HashMap<>(4);
       jsonObject.put("code",200);
       jsonObject.put("msg","查询成功");
       jsonObject.put("total",size);
       jsonObject.put("data",workForCampsites);
       return jsonObject;
   }
   /**得到未评阅学生的列表*/
  @GetMapping("/weitijiao")
    public String weitijiao(WorkForCampsiteParam workForCampsiteParam)  {
      workForCampsiteParam.setQisi((workForCampsiteParam.getQisi()-1)*workForCampsiteParam.getOffset());
      List<WorkForCampsite> workForCampsites = workForCampsiteServlce.WeiTiJiao(workForCampsiteParam);
      /**现在来计算total*/
      workForCampsiteParam.setQisi(0);
      workForCampsiteParam.setOffset(10000);
      List<WorkForCampsite> workForCampsites1 = workForCampsiteServlce.WeiTiJiao(workForCampsiteParam);
      int size = workForCampsites1.size();
      JSONObject jsonObject =new JSONObject();
      jsonObject.put("code",200);
      jsonObject.put("msg","查询成功");
      jsonObject.put("total",size);
      jsonObject.put("data",workForCampsites);
     return jsonObject.toJSONString();
   }
   /**得到具体的学生作业*/
   @GetMapping("/StuWork")
    public AjaxResult StuWork(WorkForCampsiteParam workForCampsiteParam){
       WorkForCampsite workForCampsite = workForCampsiteServlce.ChaKanZuoYe(workForCampsiteParam);
       return AjaxResult.success("查询成功",workForCampsite);
   }
   /**评阅学生作业的接口*/
   @PostMapping("/PingYueWork")
    public AjaxResult PingYueWork(WorkForCampsiteParam workForCampsiteParam){
       Date date  =new Date();
       workForCampsiteParam.setCreateTime(date);
       workForCampsiteParam.setUpdateTime(date);
       Integer integer = workForCampsiteServlce.TeaComment(workForCampsiteParam);
       return AjaxResult.success("评阅成功");
   }
   /**已评下一条接口*/
   @GetMapping("/YiPingXiaYiTiao")
   public AjaxResult YiPingXiaYiTiao(WorkForCampsiteParam workForCampsiteParam){
       /**设置一下查询所有列表*/
       workForCampsiteParam.setQisi(0);
       workForCampsiteParam.setOffset(10000);
       /**首先查找到这个列表当前的所有排序*/
       List<WorkForCampsite> workForCampsites = workForCampsiteServlce.WeiPingYue(workForCampsiteParam);
       /**创建一个存放所有学生UUID的集合(按照列表展示的顺序存放)*/
       List<String> stringList =new ArrayList<>();
       for (WorkForCampsite workForCampsite : workForCampsites) {
           stringList.add(workForCampsite.getUuid());
       }
       int i = stringList.indexOf(workForCampsiteParam.getUuid());
       /**判断这个用户是不是最后一个用户*/
       if (i<workForCampsites.size()-1) {
           String s = stringList.get(i + 1);
           /**此时再次调用查找作业的方法*/
           workForCampsiteParam.setUuid(s);
           /**此时就得到了下一条的作业详情*/
           WorkForCampsite workForCampsite = workForCampsiteServlce.ChaKanZuoYe(workForCampsiteParam);
         return AjaxResult.success("查询下一条成功",workForCampsite);
       } if (i==workForCampsites.size()-1){
           return AjaxResult.error("评阅已结束");
       }
       return null;
   }
   /**回评接口*/
   @PostMapping("/HuiPingWork")
    public AjaxResult HuiPingWork (WorkForCampsiteParam workForCampsiteParam){
       Date date =new Date();
       workForCampsiteParam.setUpdateTime(date);
       Integer integer = workForCampsiteServlce.TeaCommentAgain(workForCampsiteParam);
       return AjaxResult.success("回评成功");
   }
   /**回评回显*/
   @GetMapping("/HuiPingHuiXian")
    public AjaxResult HuiPingHuiXian(WorkForCampsiteParam workForCampsiteParam){
       WorkForCampsite workForCampsite = workForCampsiteServlce.TeacherLd(workForCampsiteParam);
       return AjaxResult.success("查询成功",workForCampsite);
   }
    /**教师上传作业pdf,word,excel等文件，需要使用文件数组*/
    @PostMapping("/UploadWorkForStudent")
    public AjaxResult UploadWorkForStudent(MultipartFile[] multipartFile){
        /**用来装载这些url，多的之间使用,隔开*/
        List<String> list =new ArrayList<>();
        /**首先进行判空，老一套了*/
        if (multipartFile==null||multipartFile.length<=0){
            return AjaxResult.error("请不要上传空文件");
        }
        /**判断文件的大小不能超过十个*/
        if (multipartFile.length>10){
            return AjaxResult.error("请不要上传大于10个文件");
        }
        /**遍历文件进oss*/
        for (int i=0;i<multipartFile.length;i++) {
            MultipartFile multipartFile1 = multipartFile[i];
            /**如果大于100M则不给他上传*/
            boolean m = checkFileSize(multipartFile1.getSize(), 100, "M");
            if (m){
                log.info("开始上传文件了");
                String fileName1 =multipartFile1.getOriginalFilename();
                String fileName = OssFileUtils.generateFileName(multipartFile1);
                String url =null;
                String s = UUID.randomUUID().toString().trim().replaceAll("-", "");
                String objectName =s+"workforstudent/" +fileName1;
                String bucketName = "campiste";
                try {
                    oss.putObject(bucketName,objectName,new ByteArrayInputStream(multipartFile1.getBytes()));
                    url = "http://campiste.oss-cn-beijing.aliyuncs.com" + "/" + objectName;
                    list.add(url);
                } catch (IOException e) {
                    e.printStackTrace();
                    log.info("第"+i+"文件上传失败");
                }

            }else {
                return AjaxResult.error("文件大小大于100M,请重新选择小的文件上传");
            }
        }
        /**将所得的URL集合转换为大的字符串*/
        String join = StringUtils.join(list, ",");
        return AjaxResult.success(join);
    }
    @Bean
    public static Client client() throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId("LTAI4FeK52KgR5GHCC21EWmY")
                // 您的AccessKey Secret
                .setAccessKeySecret("1ydOmQ3gvDRe0pCrjVOK7lKsJLs0is");
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }
    @GetMapping("/SendMessage")
    public AjaxResult SendMessage(){
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setSignName("CAMPCENTER");
        sendSmsRequest.setPhoneNumbers("15077916636");
        sendSmsRequest.setTemplateCode("SMS_229638807");
        JSONObject finalJsonParameters = new JSONObject();
       finalJsonParameters.put("name","大明星");
       finalJsonParameters.put("camp_name","创造营2021");
       sendSmsRequest.setTemplateParam(finalJsonParameters.toJSONString());
        try {
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success("发送成功");
    }
    /**新的未提交学生列表*/
    @GetMapping("/NewWeiTiJiao")
    public String NewWeiTiJiao(WorkForCampsiteParam workForCampsiteParam){
        workForCampsiteParam.setQisi((workForCampsiteParam.getQisi()-1)*workForCampsiteParam.getOffset());
        List<WeiTiJiaoStudent> weiTiJiaoStudents = weiTiJiaoStudentService.WeiTiJiaoStudent(workForCampsiteParam);
        /**现在来计算TOTAL*/
        workForCampsiteParam.setQisi(0);
        workForCampsiteParam.setOffset(10000);
        List<WeiTiJiaoStudent> weiTiJiaoStudents1 = weiTiJiaoStudentService.WeiTiJiaoStudent(workForCampsiteParam);
        int size = weiTiJiaoStudents1.size();
        JSONObject jsonObject =new JSONObject();
        jsonObject.put("msg","查询成功");
        jsonObject.put("total",size);
        jsonObject.put("data",weiTiJiaoStudents);
        jsonObject.put("code",200);
      return jsonObject.toJSONString();
    }
}

